//
//  GLPushAnimation.m
//  GLTransitionAnimationDemo
//
//  Created by 黄露 on 2019/5/31.
//  Copyright © 2019 高磊. All rights reserved.
//

#import "GLPushCustomAnimation.h"

@implementation GLPushCustomAnimation


- (void)setToAnimation:(id<UIViewControllerContextTransitioning>)contextTransition
{
    
    UIView *containerView = contextTransition.containerView;
    UIViewController *fromVC = [contextTransition viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [contextTransition viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *fromView = [contextTransition viewForKey:UITransitionContextFromViewKey] ?: fromVC.view;
    UIView *toView = [contextTransition viewForKey:UITransitionContextToViewKey] ?: toVC.view;
    [containerView addSubview:fromView];
    [containerView addSubview:toView];
    toView.frame = CGRectMake(CGRectGetWidth(containerView.bounds), 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    containerView.backgroundColor = [UIColor clearColor];
    [UIView animateWithDuration:self.duration
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut animations:^{
        CGRect endFrame = toView.frame;
        endFrame.origin.x = 0;
        toView.frame = endFrame;
    } completion:^(BOOL finished) {
        [contextTransition completeTransition:!contextTransition.transitionWasCancelled];
    }];
}

- (void)setBackAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIView *containerView = transitionContext.containerView;
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey] ?: fromVC.view;
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey] ?: toVC.view;
    toView.frame = CGRectMake(- CGRectGetWidth(containerView.bounds), 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    fromView.frame = CGRectMake(0, 0, CGRectGetWidth(containerView.bounds), CGRectGetHeight(containerView.bounds));
    [containerView addSubview:fromView];
    [containerView addSubview:toView];
    [UIView animateWithDuration:self.duration animations:^{
        CGRect toFrame = toView.frame;
        toFrame.origin.x = 0;
        toVC.view.frame = toFrame;
    } completion:^(BOOL finished) {
        if ([transitionContext transitionWasCancelled]) {
            [containerView addSubview:fromView];
        }
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];
}


@end
